<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * date: 2021-09-08 21:07:50
 * @LastEditors: Sam
 * @LastEditTime: 2022-03-10 19:28:01
 */
namespace app\api\controller;
use app\__MODULE__\model\{SurveyTheme,SurveyQuestion,SurveyOption,SurveyAnswer};
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("问卷模块")
 */
class Survey extends Base{


    /**
     * @Apidoc\Title("问卷列表")
     * @Apidoc\Url("/api/survey_list")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("[]", type="list[]",
     *      @Apidoc\Returned("id", type="int",desc="问卷id"),
     *      @Apidoc\Returned("title", type="string",desc="问卷标题"),
     *      @Apidoc\Returned("is_finish", type="int",desc="是否已完成 0未完成 1已完成")
     * )
     */
    public function list(){
        $page  = request()->param('page/d',1);
        $limit = request()->param('limit/d',10);
        $uid   = $this->get_user_id();
        $list = SurveyTheme::field('id,title')->order('sort asc')->page($page,$limit)->select()->toArray();
        if(count($list)){
            foreach ($list as $key => &$value) {
                $value['is_finish'] =  SurveyAnswer::where(['uid'=>$uid,'survey_id'=>$value['id']])->count() ? 1 : 0;
            }
        }
        json_response(1,'success',$list??[]);
    }


    /**
     * @Apidoc\Title("问卷详情")
     * @Apidoc\Url("/api/survey_detail")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("survey_id", type="int",desc="问卷id"),
     * @Apidoc\Returned("[]", type="list[]",
     *      @Apidoc\Returned("id", type="int",desc="题目ID"),
     *      @Apidoc\Returned("title", type="string",desc="题目标题"),
     *      @Apidoc\Returned("type", type="int",desc="题目类型 1 单选 2多选 3填空 4选择填空"),
     *      @Apidoc\Returned("option", type="list[]",desc="选项",
     *               @Apidoc\Returned("option_id", type="int",desc="选项id"),
     *               @Apidoc\Returned("option_name", type="string",desc="选项"),
     *               @Apidoc\Returned("option_name", type="string",desc="选项编号"),
     *  )
     * )
     */
    public function survey_detail(){
        $id = request()->param('survey_id/d');
        $uid = $this->get_user_id();
        if(!$id) json_response(0,'问卷id不得为空');
        if(!$detail = SurveyTheme::get($id)) json_response(0,'问卷不存在');
        if(SurveyAnswer::where(['uid'=>$uid,'survey_id'=>$id])->count()) json_response(0,'已经完成过该问卷调查');
        $question = SurveyQuestion::where('survey_id',$id)->field('id,survey_id,title,type')->order('sort asc')->append(['option'])->select()->toArray();
        json_response(1,'success',$question);
    }


    /**
     * @Apidoc\Title("提交问卷")
     * @Apidoc\Url("/api/survey_submit")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("survey_id", type="int",desc="问卷id"),
     * @Apidoc\Param("answer", type="json[]",desc="答案 ",
     *      @Apidoc\Param("question_id", type="int",desc="题目id "), 
     *      @Apidoc\Param("option_id", type="int",desc="选项id 多选用,号分割 "),
     *      @Apidoc\Param("answer_name", type="string",desc="填空题时填写的值 "),
     * ),
     */
    public function survey_submit(){
        $id = request()->param('survey_id/d');
        $uid = $this->get_user_id();
        if(!$id) json_response(0,'问卷id不得为空');
        $answer =  request()->post('answer','',null);

        if(!$answer) show(0,'答案不得为空');
        if(!$detail = SurveyTheme::get($id)) json_response(0,'问卷不存在');
        $answer = json_decode($answer,true);
         if(count($answer) != SurveyQuestion::where('survey_id',$id)->count()) json_response(0,'提交的答案不完整');
        Db::startTrans();
        try {
            foreach ($answer as $key => $value) {
                $question = SurveyQuestion::where('id',$value['question_id'])->find();
                if(!$question) \exception('题目不存在');
                if($question->type == 1){
                    $option  = SurveyOption::where('id',$value['option_id'])->find();
                    if(!$option)  \exception('无此选项');
                    //单选
                    if(!isset($value['option_id']) || empty($value['option_id'])) \exception('请选择选项');
                    SurveyAnswer::create([
                        'uid'  => $uid,
                        'survey_id' => $id,
                        'question_id' => $question->id,
                        'question_name' =>$question->title,
                        'type'  => 1,
                        'option_id' => $option->id,
                        'answer_number' => $option->option_number,
                        'answer_name'  => $option->option_number.'.'.$option->option_name
                    ]);
                }elseif($question->type == 2){
                    //多选
                    // $option_id  = SurveyOption::where('id','in',$value['option_id'])->cache('option_id:'.$value['option_id'])->column('id');
                    //取出选项
                    $option     = SurveyOption::where('id','in',$value['option_id'])->field('id,option_number,option_name')->select();
                    if(!isset($value['option_id']) || empty($value['option_id'])) exception('请选择选项');
                    $option_number  = SurveyOption::where('id','in',$value['option_id'])->column('option_number');
                    $answer_name = '';
                    if(!$option || !$option_number) \exception('无此选项');
                    foreach($option as $v){
                        $answer_name .= $v['option_number'].'.'.$v['option_name'].';'; 
                    }
                    SurveyAnswer::create([
                        'uid'  => $uid,
                        'survey_id' => $id,
                        'question_id' => $question->id,
                        'question_name' =>$question->title,
                        'type'  => 2,
                        'option_id' => $value['option_id'],
                        'answer_number' => implode(',',$option_number),
                        'answer_name' => $answer_name
                    ]);
                }elseif($question->type == 3){
                    //填空
                    if(!$value['answer_name']) exception('请填写填空');
                    SurveyAnswer::create([
                        'uid'  => $uid,
                        'survey_id' => $id,
                        'question_id' => $question->id,
                        'question_name' =>$question->title,
                        'type'  => 3,
                        'answer_name' =>$value['answer_name']
                    ]);
                }elseif($question->type == 4){
                    //选择填空
                      $option  = SurveyOption::where('id',$value['option_id'])->find();
                      if(!$option)  \exception('无此选项');
                      if($option->option_name == '其他' && !$value['answer_name']) \exception('其他选项请填写');
                       SurveyAnswer::create([
                        'uid'  => $uid,
                        'survey_id' => $id,
                        'question_id' => $question->id,
                        'question_name' =>$question->title,
                        'type'  => 4,
                        'answer_name' => isset($value['answer_name']) ? $option->option_number.'.'.$option->option_name.':'.$value['answer_name'] : '',
                        'answer_number' => $option->option_number
                    ]);
                }
            }
   
            Db::commit();
        } catch (\Exception $e) {
             Db::rollback();
             json_response(0,$e->getMessage());
        }
        json_response(1,'提交成功');
    }
}